//
//  CSL_Player_ViewController.m
//  HZ_Beautiful_Music
//
//  Created by dllo on 16/4/7.
//  Copyright © 2016年 ui. All rights reserved.
//

#import "CSL_Player_ViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import "CSLPlayer.h"

#import "WDGDatabaseTool.h"
#import "CSL_CollecModel.h"

@interface CSL_Player_ViewController ()
@property (nonatomic, strong) CSL_Data_MvListModel *listModel;

@property (nonatomic, strong) CSLPlayer *csPlayer;

@property (nonatomic, strong) AVPlayer *player;
@property (nonatomic, strong) AVPlayerItem *playerItem;
@property (nonatomic, assign) CGFloat width;
@property (nonatomic, assign) CGFloat height;
@property (nonatomic, strong) UISlider *slider;//进度条
@property (nonatomic, strong) UILabel *currentTimeLabel;//当前播放时间
@property (nonatomic, strong) UILabel *systemTimeLabel;//系统时间
@property (nonatomic, strong) UIView *backView;//上面一层Viewd
@property (nonatomic, assign) CGPoint startPoint;
@property (nonatomic, assign) CGFloat systemVolume;
@property (nonatomic, strong) UISlider *volumeViewSlider;
@property (nonatomic, strong) UIActivityIndicatorView *activity;//系统菊花
@property (nonatomic, strong) UIProgressView *progress;//缓冲条
@property (nonatomic, strong) UIView *topView;
@property (nonatomic, strong) UIButton *collecButton;//收藏按钮
@property (nonatomic, strong) WDGDatabaseTool *collectionHandler;
@property (nonatomic, strong) CSL_CollecModel *collecModel;
@property (nonatomic, strong) NSMutableArray *collecArray;
@property (nonatomic, assign) BOOL isCollec;
@property (nonatomic, strong) WDGWhereCondition *wherecondition;


@end

@implementation CSL_Player_ViewController
-(instancetype)initWithCSL_Data_MvListModel:(CSL_Data_MvListModel *)data_mvListModel{
    self = [super init];
    if (self) {
        self.listModel = data_mvListModel;
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated {
    
    self.csPlayer = [CSLPlayer shareAVPlayer];
    [self.csPlayer pause];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [self.csPlayer play];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden=YES;
    self.view.backgroundColor = [UIColor colorWithWhite:0.692 alpha:1.000];
    

    NSLog(@"gdsf%@", _listModel.url);
    NSLog(@"fdsfs%@", _listModel.duration);//持续时间

    [WDGDatabaseTool creatTableWithSQL:@"CREATE TABLE if not exists collection(pic_url text NOT NULL UNIQUE, title text NOT NULL UNIQUE, name text  NOT NULL UNIQUE, url text  NOT NULL UNIQUE)"];
    self.collectionHandler = [WDGDatabaseTool DBManageWithTableName:@"collection"];
    [WDGDatabaseTool openDebugMode:YES];
    
    NSLog(@"%@", _listModel.url);
    NSLog(@"%@", _listModel.duration);//持续时间

    _width = [[UIScreen mainScreen]bounds].size.height;
    _height = [[UIScreen mainScreen]bounds].size.width;
    [self CreatePlayer];
    [self CreateCollecButton];
//    [self IsChangeImage];
    
    
    NSNotificationCenter *hiddenCollecButton = [NSNotificationCenter defaultCenter];
    [hiddenCollecButton addObserver:self selector:@selector(hiddenCollecButton:) name:@"hiddenCollecButton" object:nil];
    
    NSNotificationCenter *hiddenCollec = [NSNotificationCenter defaultCenter];
    [hiddenCollec addObserver:self selector:@selector(hiddenCollec:) name:@"hiddenCollec" object:nil];
    
    NSNotificationCenter *hiddencsl = [NSNotificationCenter defaultCenter];
    [hiddencsl addObserver:self selector:@selector(hiddencsl:) name:@"hiddencsl" object:nil];
   
}

#pragma mark - 收藏按钮
-(void)CreateCollecButton{
    self.collecButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    _collecButton.backgroundColor = [UIColor redColor];
     _collecButton.frame = CGRectMake(_topView.bounds.size.width/2, _topView.bounds.size.height/2.5, _topView.bounds.size.width/18, _topView.bounds.size.height/2);
    
    [_collecButton setBackgroundImage:[UIImage imageNamed:@"no_collection"] forState:UIControlStateNormal];
    [self IsChangeImage];
    
    
    [_collecButton addTarget:self action:@selector(CollectionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:_collecButton];
}

-(void)CollectionButtonAction:(UIButton *)sender {
    Search_MV_Data_mvListModel *mv_Data_mvListModel = _mv_dataModel.mvList[0];
    
    [_collectionHandler openDatabase];
    if (self.isCollec) {
        
            self.wherecondition = [WDGWhereCondition conditionWithColumnName:@"url" Operator:@"=" Value:_collecModel.url];
            
            [_collectionHandler deleteDataWithWhereCondition:_wherecondition];
            [_collecButton setBackgroundImage:[UIImage imageNamed:@"no_collection"] forState:UIControlStateNormal];
            _isCollec = NO;
            
        } else {
            
            [_collectionHandler insertDataWithDictionary:@{@"pic_url" : _mv_dataModel.picUrl, @"title" : _mv_dataModel.videoName, @"name":_mv_dataModel.singerName, @"url" : mv_Data_mvListModel.url}];
            [_collecButton setBackgroundImage:[UIImage imageNamed:@"collection"] forState:UIControlStateNormal];
            _isCollec = YES;
          
        }
    [_collectionHandler closeDatabase];
}

-(void)IsChangeImage{

    self.collecArray = [NSMutableArray arrayWithCapacity:0];
    [_collectionHandler openDatabase];
        for (NSDictionary *Dic in [_collectionHandler selectAllData]) {
            _collecModel = [[CSL_CollecModel alloc] initWithDataSource:Dic];
            [_collecArray addObject:_collecModel];
            
            if ([_collecModel.url isEqualToString:_mv_Data_mvListModel.url]) {
                
                [_collecButton setBackgroundImage:[UIImage imageNamed:@"collection"] forState:UIControlStateNormal];
                self.isCollec = YES;
                
            } else {
                
                [_collecButton setBackgroundImage:[UIImage imageNamed:@"no_collection"] forState:UIControlStateNormal];
                self.isCollec = NO;
            }
        }
    [_collectionHandler closeDatabase];
}

#pragma mark - 播放
-(void)CreatePlayer {
//   self.player = [CSLPlayer shareAVPlayer];
    if (_listModel.url) {
        self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_listModel.url]];
//        [self.player playWithUrl:_listModel.url];

        if (_listModel.url == nil) {
            NSLog(@"aaaaaaaaaaaaaaaaaaaaaaa");
        } else {
            self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_listModel.url]];
        }
    } else if(_mv_Data_mvListModel.url){
        self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_mv_Data_mvListModel.url]];
//        [self.player playWithUrl:_mv_Data_mvListModel.url];
    } else if(_collecMVModel.url){
     self.playerItem = [AVPlayerItem playerItemWithURL:[NSURL URLWithString:_collecMVModel.url]];
//        [self.player playWithUrl:_collecMVModel.url];
    }
    self.player = [AVPlayer playerWithPlayerItem:_playerItem];
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:_player];
    playerLayer.frame = CGRectMake(0, 0, _width, _height);
    playerLayer.videoGravity = AVLayerVideoGravityResize;
    [self.view.layer addSublayer:playerLayer];
    [_player play];
    
    //  AVPlayer 播放完成通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemFailedToPlayToEndTimeNotification object:_player.currentItem];
    self.backView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _width, _height)];
    [self.view addSubview:_backView];
    _backView.backgroundColor = [UIColor clearColor];
    
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _width, _height*0.15)];
    _topView.backgroundColor = [UIColor blackColor];
    _topView.alpha = 0.5;
    [_backView addSubview:_topView];
    
    [self.playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];//监听loadedTimeRanges属性
    [self CreateProgress];
    [self CreateSlider];
    [self createCurrentTimeLabel];
    [self createButton];
    [self backButton];
    [self createGesture];
    [self customVideoSlider];
    
    self.activity = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    
    _activity.center = _backView.center;
    [self.view addSubview:_activity];
    [_activity startAnimating];
    
    //延迟线程
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [UIView animateWithDuration:0.5 animations:^{
            _activity.alpha = 0;
        }];
    });
    
    // 计时器
    [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(Stack) userInfo:nil repeats:YES];
}

#pragma mark - 横屏代码
-(BOOL) shouldAutorotate {
    return NO;
}//NS_AVAILABLE_IOS(6_0);当前viewcontroller是否支持横屏

-(UIInterfaceOrientationMask) supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}//当前viuewcontroller支持哪些转动方向

-(UIInterfaceOrientation)preferredInterfaceOrientationForPresentation {
    return UIInterfaceOrientationLandscapeRight;
}

-(BOOL)prefersStatusBarHidden {
    return NO;//返回NO表示要显示,返回YES表示hiden
}

#pragma mark - 创建UISlider
-(void)CreateSlider {
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/8, self.view.bounds.size.height/1.885, _width*0.78, self.view.bounds.size.height/45)];
    [_backView addSubview:_slider];
    [_slider setThumbImage:[UIImage imageNamed:@"yuan"] forState:UIControlStateNormal];
    [_slider addTarget:self action:@selector(progressSlider:) forControlEvents:UIControlEventValueChanged];
    _slider.minimumTrackTintColor = [UIColor colorWithRed:30/255.0 green:80/255.0 blue:100/255.0 alpha:1];
}

#pragma mark - slider滑动时间
-(void)progressSlider:(UISlider *)slider{
//拖动改变视频播放进度
    if (_player.status == AVPlayerStatusReadyToPlay) {
        //计算出当前的拖动秒数
        CGFloat total = (CGFloat)_playerItem.duration.value/_playerItem.duration.timescale;
        
        NSInteger dragedSeconds = floorf(total * slider.value);
        // 转换成CMTime才能给player来控制播发进度
        CMTime dragedCMTime = CMTimeMake(dragedSeconds, 1);
        [_player pause];
        [_player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
            [_player play];
        }];
    }
}

#pragma mark - 创建UIProgressView
-(void)CreateProgress{
    self.progress = [[UIProgressView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/8, self.view.bounds.size.height/1.85, _width*0.78, self.view.bounds.size.height/45)];
    [_backView addSubview:_progress];
}





-(void)leftBarButtonItemAction:(UIBarButtonItem *)sender {
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:1.000 green:0.263 blue:0.222 alpha:1.000];
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        NSTimeInterval timeTnterVal = [self availableDuration];//计算缓冲进度
        NSLog(@"%f", timeTnterVal);
        CMTime duration = self.playerItem.duration;
        CGFloat totalDuration = CMTimeGetSeconds(duration);
        [self.progress setProgress:timeTnterVal / totalDuration animated:NO];
    }
}

-(NSTimeInterval)availableDuration {
    NSArray *loadedTimeRanges = [[_player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadedTimeRanges.firstObject CMTimeRangeValue];//获取缓冲区域
    float startSeconds = CMTimeGetSeconds(timeRange.start);
    float durationSeconds = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSeconds + durationSeconds;//计算缓冲进度
    return result;
}

-(void)customVideoSlider {
    UIGraphicsBeginImageContextWithOptions((CGSize){1,1}, NO, 0.0f);
    UIImage *transparentImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndPDFContext();    
    [self.slider setMaximumTrackImage:transparentImage forState:UIControlStateNormal];
}

#pragma mark - 创建播放时间
-(void)createCurrentTimeLabel {
    self.currentTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(_width *0.86, self.view.bounds.size.height/1.89, self.view.bounds.size.width/4.1, self.view.bounds.size.height/33)];
    [self.backView addSubview:_currentTimeLabel];
    _currentTimeLabel.textColor = [UIColor whiteColor];
    _currentTimeLabel.font = [UIFont systemFontOfSize:12];
    _currentTimeLabel.text = @"00:00/00:00";
    
}

#pragma mark - 计时器事件
-(void)Stack {
    if (_playerItem.duration.timescale != 0) {
        _slider.maximumValue = 1;//音乐总共时长
        _slider.value = CMTimeGetSeconds([_playerItem currentTime]) / (_playerItem.duration.value / _playerItem.duration.timescale);//当前进度
        //    当前进度时间progress
        NSInteger proMin = (NSInteger)CMTimeGetSeconds([_player currentTime]) / 60;//当前秒
        NSInteger proSec = (NSInteger)CMTimeGetSeconds([_player currentTime]) % 60;//当前分钟
        
        //        duration 总时长
        NSInteger durMin = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale / 60;//总秒
        NSInteger durSec = (NSInteger)_playerItem.duration.value / _playerItem.duration.timescale % 60;//总分钟
        self.currentTimeLabel.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", (long)proMin, (long)proSec, (long)durMin, (long)durSec];
    }
    if (_playerItem.status == AVPlayerStatusReadyToPlay) {
        [_activity stopAnimating];
    } else {
        [_activity startAnimating];
    }
}

#pragma mark - 播放按钮
-(void)createButton {
    UIButton *startButton = [UIButton buttonWithType:UIButtonTypeCustom];
    startButton.frame = CGRectMake(self.view.bounds.size.width/40, self.view.bounds.size.height/1.95, self.view.bounds.size.width/13, self.view.bounds.size.height/23);
    [self.backView addSubview:startButton];
    if (_player.rate == 1.0) {
        [startButton setBackgroundImage:[UIImage imageNamed:@"pauseBtn"] forState:UIControlStateNormal];
    } else {
        [startButton setBackgroundImage:[UIImage imageNamed:@"playBtn"] forState:UIControlStateNormal];
    }
    [startButton addTarget:self action:@selector(startAction:) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - 播放暂停按钮方法
-(void)startAction:(UIButton *)button {
    if (button.selected) {
        [_player play];
        [button setBackgroundImage:[UIImage imageNamed:@"pauseBtn"] forState:UIControlStateNormal];
    } else {
        [_player pause];
        [button setBackgroundImage:[UIImage imageNamed:@"playBtn"] forState:UIControlStateNormal];
    }
    button.selected = !button.selected;
}

#pragma mark - 返回按钮方法
-(void)backButton {
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(self.view.bounds.size.width/25, self.view.bounds.size.height/25, self.view.bounds.size.width/13, self.view.bounds.size.height/25);
    [button setBackgroundImage:[UIImage imageNamed:@"iconfont-back"] forState:UIControlStateNormal];
    [_topView addSubview:button];
    [button addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.player pause];
}

#pragma mark - 创建手势
-(void)createGesture {
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [self.view addGestureRecognizer:tap];
    
    //    获取系统音量
    MPVolumeView *volumeView = [[MPVolumeView alloc] init];
    _volumeViewSlider = nil;
    for (UIView *view in [volumeView subviews]) {
        if ([view.class.description isEqualToString:@"MPVolumeSlider"]) {
            _volumeViewSlider = (UISlider *)view;
            break;
        }
    }
    _systemVolume = _volumeViewSlider.value;
}

#pragma mark - 轻拍方法
-(void)tapAction:(UITapGestureRecognizer *)tap {
    if (_backView.alpha == 1) {
        [UIView animateWithDuration:0.5 animations:^{
            _backView.alpha = 0;
        }];
    } else if (_backView.alpha == 0){
        [UIView animateWithDuration:0.5 animations:^{
            _backView.alpha = 1;
        }];
    }
    if (_backView.alpha == 1) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(7 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:0.5 animations:^{
                _backView.alpha = 0;
            }];
        });
    }
}

#pragma mark - 滑动调整音量大小
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (event.allTouches.count == 1) {
        //保存当前触摸的位置
        CGPoint point = [[touches anyObject] locationInView:self.view];
        _startPoint = point;
    }
}

-(void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    if (event.allTouches.count == 1) {
        //计算位移
        CGPoint point = [[touches anyObject] locationInView:self.view];
        float dy = point.y - _startPoint.y;
        int index = (int)dy;
        if (index > 0) {
            if (index % 5 == 0) {//每十个像素声音减一格
                NSLog(@"%.2f", _systemVolume);
                if (_systemVolume > 0.1) {
                    _systemVolume = _systemVolume - 0.05;
                    [_volumeViewSlider setValue:_systemVolume animated:YES];
                    [_volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }
        } else {
            if (index % 5 == 0) {//每十个像素增加一格
                NSLog(@"+x == %d", index);
                NSLog(@"%.2f", _systemVolume);
                if (_systemVolume >= 0 && _systemVolume < 1) {
                    _systemVolume = _systemVolume +0.05;
                    [_volumeViewSlider setValue:_systemVolume animated:YES];
                    [_volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
                }
            }
        }
    }
}

-(void)moviePlayDidEnd:(id)sender {
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

-(void)backButtonAction{
    [_player pause];
    self.navigationController.navigationBarHidden=NO;
    [self dismissViewControllerAnimated:YES completion:^{}];
}

-(void)hiddenCollecButton:(NSNotification *)hiddenCollecButton{
    _collecButton.hidden = YES;
}

-(void)hiddenCollec:(NSNotification *)hiddenCollec{
    _collecButton.hidden = YES;
}

-(void)hiddencsl:(NSNotification *)hiddencsl{
    _collecButton.hidden = YES;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
